package com.lfy.kcat.content.biz.impl;

import cn.dev33.satoken.secure.SaBase64Util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lfy.kcat.content.biz.AuthCheckService;
import com.lfy.kcat.content.domain.DramaAuth;
import com.lfy.kcat.content.domain.Dramas;
import com.lfy.kcat.content.feign.CamundaFeignClient;
import com.lfy.kcat.content.mapper.DramaAuthMapper;
import com.lfy.kcat.content.mapper.DramasMapper;
import com.lfy.kcat.content.service.DramaAuthService;
import com.lfy.kcat.content.vo.ManualAuthTaskVo;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.dto.DramaAuthCompleteDTO;
import org.dromara.common.core.dto.DramaAuthManualTaskDTO;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * @author leifengyang
 * @version 1.0
 * @date 2025/9/12 10:56
 * @description:
 */
@Slf4j
@Service
public class AuthCheckServiceImpl implements AuthCheckService {

    @Autowired
    DramaAuthService dramaAuthService;

    @Autowired
    CamundaFeignClient camundaFeignClient;

    @Autowired
    DramasMapper dramasMapper;
    @Autowired
    DramaAuthMapper  dramaAuthMapper;


    @Override
    public String getProcessIdByDramaId(Long dramaId) {
        LambdaQueryWrapper<DramaAuth> wrapper = Wrappers.lambdaQuery(DramaAuth.class)
            .eq(DramaAuth::getDramaId, dramaId);
        DramaAuth dramaAuth = dramaAuthMapper.selectOne(wrapper);
        return dramaAuth.getProcessId();
    }

    @Override
    public Integer getAiCheckStatus(Long dramaId) {
        //1、知道这个短剧对应哪个审核流程(去数据库查询)
//        DramaAuth auth = dramaAuthService.getOne(Wrappers.lambdaQuery(DramaAuth.class)
//            .eq(DramaAuth::getDramaId, dramaId));
        //拿到审核的流程id
        String processId = getProcessIdByDramaId(dramaId);
        Integer aiCheckStatus = 0;


        //TODO 2、用这个流程id让流程框架查一下对应的所有变量值
        R<Map<String, Object>> r = camundaFeignClient.getProcessVariables(processId);
        if(r.getCode() == 200){
            Map<String, Object> data = r.getData();
            log.info("从远程获取到流程变量数据：{}",data);

            // 安全处理authName变量
            int authName = 1;
            Object authNameObj = data.get("authName");
            if (authNameObj != null) {
                String authNameStr = authNameObj.toString().trim();
                if ("0".equals(authNameStr)) {
                    authName = 0;
                } else if ("1".equals(authNameStr)) {
                    authName = 1;
                } else if ("FAILED".equalsIgnoreCase(authNameStr)) {
                    authName = 0;
                } else if ("PASSED".equalsIgnoreCase(authNameStr)) {
                    authName = 1;
                }
            }

            // 安全处理authDescription变量
            int authDescription = 1;
            Object authDescriptionObj = data.get("authDescription");
            if (authDescriptionObj != null) {
                String authDescriptionStr = authDescriptionObj.toString().trim();
                if ("0".equals(authDescriptionStr)) {
                    authDescription = 0;
                } else if ("1".equals(authDescriptionStr)) {
                    authDescription = 1;
                } else if ("FAILED".equalsIgnoreCase(authDescriptionStr)) {
                    authDescription = 0;
                } else if ("PASSED".equalsIgnoreCase(authDescriptionStr)) {
                    authDescription = 1;
                }
            }

            //给前端一个参考结果
            if(authName == 1 && authDescription == 1){
                aiCheckStatus = 1;
            }else {
                aiCheckStatus = 0;
            }
        }

        return aiCheckStatus;
    }



    @Transactional
    @Override
    public void saveManualAuthData(ManualAuthTaskVo manualAuthTaskVo,
                                   String authHeader) {

        //3、当前登录到系统中的人是谁。
        String payLoad = authHeader.split("\\.")[1];
        String decode = SaBase64Util.decode(payLoad);
        //这里是将用户数据打包成对象
        JSONObject jsonObject = JSON.parseObject(decode);
        String userName = jsonObject.get("userName").toString();


        String processId = getProcessIdByDramaId(manualAuthTaskVo.getDramaId());

        //TODO 2、远程调用流程引擎，完成人工审核任务； approve 表示成功与失败
        // Dramas::getDramaId === 对应的启动的流程
        // userName, processId： 人工审核任务
        DramaAuthManualTaskDTO dto = new DramaAuthManualTaskDTO();

        dto.setDramaId(manualAuthTaskVo.getDramaId());
        dto.setUserName(userName);
        dto.setProcessId(processId);
        dto.setAuditReason(manualAuthTaskVo.getAuditReason());
        dto.setAuditStatus(manualAuthTaskVo.getAuditStatus());

        camundaFeignClient.claimManualAuthTaskAndComplete(dto);


    }

    @Override
    public void completeAuthUpdateDb(DramaAuthCompleteDTO dto) {
        log.info("短剧审核数据库状态修改：{}",dto);
        //1、保存审核状态数据； 指定修改对应的字段
        LambdaUpdateWrapper<Dramas> wrapper = Wrappers.lambdaUpdate(Dramas.class)
            .set(Dramas::getAuditStatus, dto.getAuditStatus())
            .set(Dramas::getAuditReason, dto.getAuditReason())
            .eq(Dramas::getDramaId, dto.getDramaId());
        dramasMapper.update(wrapper);

        //2、保存审核记录表
        LambdaUpdateWrapper<DramaAuth> updateWrapper = Wrappers.lambdaUpdate(DramaAuth.class)
            .set(DramaAuth::getAuthStatus,
                dto.getAuditStatus().equals("2") ? "-1" : "1")
            .eq(DramaAuth::getDramaId, dto.getDramaId());
        dramaAuthMapper.update(updateWrapper);
    }
}
